<!--
* description: 备件销售入库
* author: chenweilin
* createdDate: 2021-7-16
-->

<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :stripe="false"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-init-table="true"
      :callback-obj="callbackObj"
      :dynamic-api-style="'restful'"
    >
    </one-table-template>
    <Details ref="partsDetails"/>
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/pa/apiBranchWarehouse'
import request from '@/utils/request'
import { exportExcel } from '@/utils/getTimeString.js'
import Vue from 'vue'

export default {
  name: 'SparePartsSoldOut',

  components: {
    OneTableTemplate,
    Details: () => import('./partsDetails')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      editRowData: {},
      selectiondata: [],
      // 网格查询API配置对象
      apiConfig: api.queryInStorageInfo,

      callbackObj: {
        // 手动勾选时
        // onCheckSelect: (selection, row) => {
        //   this.selectiondata = selection
        // },
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectiondata = selection
        }
      },
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'comKey2',
          type: '',
          size: 'small',
          name: '',
          position: 'left',
          clickEvent: () => this.exportExcelDetails(),
          text: '导出',
          disabled: false
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey10',
              labelName: '入库关联单号',
              codeField: 'relateOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey30',
              labelName: '制单人',
              codeField: 'creator',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey40',
              labelName: '入库单号',
              codeField: 'inStoreCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey50',
              labelName: '入库日期：',
              codeField: 'beginDate,endDate',
              component: () =>
                import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              isMul: false,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey60',
              labelName: '入库类型：',
              codeField: 'billType',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: 'IS001', statusText: '采购入库' },
                { statusId: 'IS002', statusText: '直营采购入库' },
                { statusId: 'IS003', statusText: '外采入库' },
                { statusId: 'IS004', statusText: '维修出库退货入库' },
                { statusId: 'IS005', statusText: '内部领用退货入库' },
                // { statusId: 'IS006', statusText: '销售退货入库' }
              ],
              type: 'inputText',
              isMul: false,
              isMust: true,
              span: 6
            },
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'inStoreCode',
              label: '入库单编号',
              isComponent: true,
              width: 165,
              comps: [
                {
                  compKey: 'propKey1',
                  codeField: 'inStoreCode',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => {
                    var inStoreCode = this.$utils.deepCopy(this.$refs['multipleTable'].list[index]).inStoreCode
                    this.$refs['partsDetails'].open(inStoreCode)
                    this.$refs['partsDetails'].dialogVisible = true 
                  }
                }
              ]
            },
            {
              prop: 'billTypeCn',
              label: '入库类型',
            },
            {
              prop: 'relateOrderCode',
              label: '入库关联单号',
            },
            {
              prop: 'inStoreAmount',
              label: '总金额',
            },
            {
              prop: 'inStoreDate',
              label: '入库时间',
            },
            {
              prop: 'creator',
              label: '制单人',
            }
            // {
            //   prop: 'partNo',
            //   label: '备件编码',
            // },
            // {
            //   prop: 'outStoreQty',
            //   label: '出库数量',
            // },
            // {
            //   prop: 'salePrice',
            //   label: '出库单价',
            // },
            // {
            //   prop: 'saleAmount',
            //   label: '出库总金额',
            // }
          ],

      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          relateOrderCode: '',
          creator: '',
          inStoreCode: '',
          beginDate: '',
          endDate: '',
          billType: ''
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
      wareHouseOptions: []
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
    // 或取仓库数据
    // this.loadWarehouseData()
  },

  methods: {
    valChange(val, row, col) {
      const target = row['options'].find(opt => opt.warehouseId === val)
      this.$set(row, 'warehouseInfo', target)
      this.$set(row, 'usableStockQty', target['usableStockQty'])
    },
    visChange(isOpen, row, col) {
      if (!isOpen) return
      this.loadWarehouseData(row)
    },
    loadWarehouseData(row) {
      this.$requestAPI({
        apiUrl: '/mp/e3sh/spareparts/nodestorehouse/sparePartsSoldOutService/findStorageAndWarehouse.do',
        variables: { partId: row['partId'], partNo: row['partNo'] }
      }).then(res => {
        if (res.result === '1') {
          this.$set(row, 'options', res.rows)
        } else {
          this.$message(res.msg ? res.msg : '')
        }
      }).catch(err => {
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      })
    },
    exportExcelDetails() {
      exportExcel(this.formField, api.WarehousingExportDetails.APIUrl, api.WarehousingExportDetails.ServiceCode, '入库明细数据')
    }
  }
}
</script>
